package com.tnxst.phexamination.fragment.follow;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.bigkoo.pickerview.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.tnxst.phexamination.R;
import com.tnxst.phexamination.constant.HISConfig;
import com.tnxst.phexamination.databinding.DoorRecordFirstPhthisisBinding;
import com.tnxst.phexamination.databinding.DoorRecordPhthisisFollowupBinding;
import com.tnxst.phexamination.dto.InhabitantDTO;
import com.tnxst.phexamination.dto.TbFirstFollowDTO;
import com.tnxst.phexamination.dto.TbFollowDTO;
import com.tnxst.phexamination.dto.TbPatientDTO;
import com.tnxst.phexamination.public_health_docking_interface.TuberculosisInterface;
import com.tnxst.phexamination.utils.GsonUtils;
import com.tnxst.phexamination.utils.PictureFileUtil;
import com.tnxst.phexamination.utils.ReflectUtils;
import com.tnxst.phexamination.utils.StringUtils;
import com.tnxst.phexamination.utils.Utils;
import com.tnxst.phexamination.utils.WebServiceUtils;
import com.tnxst.phexamination.viewmodel.GlobalViewModel;

import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import worker8.com.github.radiogroupplus.RadioGroupPlus;

public class PhthisisFollowFragment extends Fragment implements CompoundButton.OnCheckedChangeListener{

    private GlobalViewModel viewModel;

    private Context context;

    private DoorRecordPhthisisFollowupBinding binding;

    private InhabitantDTO inhabitantDTO;

    private TbFollowDTO tbFollowDTO;

    private List<Map<String,Object>> otherText;

    private TbPatientDTO tbPatientDTO;

    //新增定位功能及拍照功能的控件
    private EditText address;

    private ImageView picture1;

    private ImageView picture2;

    private ImageView picture3;

    private Switch aSwitch;

    private Button start;

    private TextView del1;

    private TextView del2;

    private TextView del3;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        binding = DataBindingUtil.inflate(inflater, R.layout.door_record_phthisis_followup, container, false);
        context = container.getContext();
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(requireActivity()).get(GlobalViewModel.class);
        initData();
        initView();
        initAddress();
    }

    private void initAddress() {
        address = binding.include.findViewById(R.id.editTextTextPersonName33);
        picture1 = binding.include.findViewById(R.id.image1);
        picture2 = binding.include.findViewById(R.id.image2);
        picture3 = binding.include.findViewById(R.id.image3);
        aSwitch = binding.include.findViewById(R.id.isFinish);
        start = binding.include.findViewById(R.id.button22);
        del1 = binding.include.findViewById(R.id.text1);
        del2 = binding.include.findViewById(R.id.text2);
        del3 = binding.include.findViewById(R.id.text3);
        viewModel.getAddressUtils().getAddress(address, getActivity());
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PictureFileUtil.showAlbum(PhthisisFollowFragment.this, PictureConfig.CHOOSE_REQUEST);
            }
        });
        del1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFollowDTO.setPicturePath1("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            }
        });
        del2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFollowDTO.setPicturePath2("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            }
        });
        del3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tbFollowDTO.setPicturePath3("");
                Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);
            }
        });

        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b)
                    tbFollowDTO.setIsFinish(1);
                else
                    tbFollowDTO.setIsFinish(0);
            }
        });

        if (StringUtils.isNotNull(tbFollowDTO.getPicturePath1()))
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath1(), picture1);
        if (StringUtils.isNotNull(tbFollowDTO.getPicturePath2()))
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath2(), picture2);
        if (StringUtils.isNotNull(tbFollowDTO.getPicturePath3()))
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath3(), picture3);
        if (StringUtils.isNotNull(tbFollowDTO.getAddress())){
            address.setText(tbFollowDTO.getAddress());
        } else{
            viewModel.getAddressUtils().getAddress(address, getActivity());
        }

        if (tbFollowDTO.getIsFinish() == 0)
            aSwitch.setChecked(false);
        else
            aSwitch.setChecked(true);

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            // 图片选择结果回调
            tbFollowDTO.setPicturePath1("");
            tbFollowDTO.setPicturePath2("");
            tbFollowDTO.setPicturePath3("");
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture1);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture2);
            Utils.loadChatImage(getActivity(),getResources().getDrawable(R.drawable.no_image), picture3);

            List<LocalMedia> selectListPic = PictureSelector.obtainMultipleResult(data);
            tbFollowDTO.setPicturePath1(selectListPic.size() > 0 ? selectListPic.get(0).getRealPath() : "");
            tbFollowDTO.setPicturePath2(selectListPic.size() > 1 ? selectListPic.get(1).getRealPath() : "");
            tbFollowDTO.setPicturePath3(selectListPic.size() > 2 ? selectListPic.get(2).getRealPath() : "");
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath1(), picture1);
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath2(), picture2);
            Utils.loadChatImage(getActivity(),tbFollowDTO.getPicturePath3(), picture3);
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        //病人信息
        binding.editText2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String idCard = s.toString();
                if (idCard.length() >= 2 ){
                    List<InhabitantDTO> dtoList = viewModel.getInhabitantRepository().findByFieldList("NAME", idCard);
                    if (!CollectionUtils.isEmpty(dtoList)){
                        InhabitantDTO i = dtoList.get(0);
                        if (i != null){
                            inhabitantDTO = i;
//                            if (StringUtils.isNotNull(HISConfig.PRODUCT_CODE)){
//                                TuberculosisInterface.verifyIsTbPatient(inhabitantDTO.getID(), new WebServiceUtils.Response<Map>() {
//                                    @Override
//                                    public void onSuccess(Map result) {
//                                        String is = result.get("Msg").toString();
//                                        if ("1.0".equals(is)){
//                                            return;
//                                        }
//                                    }
//                                    @Override
//                                    public void onError(String error) {
//                                        Utils.Toast(context,"验证患者是否失败！\n失败原因：" + error);
//                                    }
//                                });
//                            }
                            setInhabitantView();
                        }else {
                            clearInhabitantView();
                        }
                    }else {
                        clearInhabitantView();
                        inhabitantDTO = null;
                    }
                }
            }
        });

        //药物不良反应
        binding.radioGroupPlus0211.setOnCheckedChangeListener(new RadioGroupPlus.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroupPlus group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButton2401:
                        binding.editTextTextPersonName10.setEnabled(false);
                        break;
                    case R.id.radioButton2411:
                        binding.editTextTextPersonName10.setEnabled(true);
                        break;
                }
            }
        });

        //并发症或合并症
        binding.radioGroupPlus02111.setOnCheckedChangeListener(new RadioGroupPlus.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroupPlus group, int checkedId) {
                switch (checkedId){
                    case R.id.radioButton24011:
                        binding.editTextTextPersonName11.setEnabled(false);
                        break;
                    case R.id.radioButton24111:
                        binding.editTextTextPersonName11.setEnabled(true);
                        break;
                }
            }
        });

        if (StringUtils.isNull(binding.textView270.getText().toString()))
            binding.textView270.setText(Utils.getTime(new Date()));
        //停止治疗时间
        binding.textView270.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView270.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("停止治疗时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        if (StringUtils.isNull(binding.textView271.getText().toString()))
            binding.textView271.setText(Utils.getTime(new Date()));
        //随访时间
        binding.textView271.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView271.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("停止治疗时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        if (StringUtils.isNull(binding.textView272.getText().toString()))
            binding.textView272.setText(Utils.getTime(new Date()));
        //下次随访时间
        binding.textView272.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        binding.textView272.setText(Utils.getTime(date));
                    }
                })
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setTitleText("停止治疗时间")
                        .setTitleColor(Color.WHITE)//标题文字颜色
                        .setSubmitColor(Color.parseColor("#43c489"))
                        .setCancelColor(Color.parseColor("#43c489"))
                        .setTitleBgColor(Color.parseColor("#43c489"))
                        .setDividerColor(Color.parseColor("#43c489"))
                        .setTextColorCenter(Color.parseColor("#43c489"))
                        .setTitleSize(14)
                        .setContentSize(14)
                        .setSubCalSize(14)
                        .build();

                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
            }
        });

        binding.button47.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideAddFragment();
            }
        });

        //保存
        binding.button48.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tbFollowDTO.setAddress(address.getText().toString());
                if (StringUtils.isNull(tbFollowDTO.getAddress())
                        || (StringUtils.isNull(tbFollowDTO.getPicturePath1())
                        && StringUtils.isNull(tbFollowDTO.getPicturePath2())
                        && StringUtils.isNull(tbFollowDTO.getPicturePath3()))){
                    Utils.Toast(context,"请完善地址信息或者拍摄现场图片后再保存！");
                    return;
                }
                if (inhabitantDTO == null){
                    Utils.Toast(context,"请完善病人信息！");
                    return;
                }
                tbFollowDTO.setPersonID(inhabitantDTO.getID());
                tbFollowDTO.setUpload("0");
                tbFollowDTO.setPersonName(inhabitantDTO.getNAME());
                save();
                if (StringUtils.isNull(tbFollowDTO.getID()))
                    tbFollowDTO.setID(UUID.randomUUID().toString());
                viewModel.getTbFollowRepository().insert(tbFollowDTO);
                Utils.Toast(context,"保存本地成功！");
                hideAddFragment();
            }
        });


        binding.radioButton27.setOnCheckedChangeListener(this);
        binding.radioButton28.setOnCheckedChangeListener(this);
        binding.radioButton29.setOnCheckedChangeListener(this);
        binding.radioButton32.setOnCheckedChangeListener(this);
        binding.radioButton33.setOnCheckedChangeListener(this);
        binding.radioButton34.setOnCheckedChangeListener(this);
        binding.radioButton35.setOnCheckedChangeListener(this);
        binding.radioButton36.setOnCheckedChangeListener(this);
        binding.radioButton37.setOnCheckedChangeListener(this);
        binding.radioButton38.setOnCheckedChangeListener(this);
        binding.radioButton39.setOnCheckedChangeListener(this);

    }

    /**
     * 初始化数据
     */
    private void initData() {
        Bundle arguments = getArguments();

        if (arguments == null){
            tbFollowDTO = new TbFollowDTO();
            otherText = new ArrayList<>();
        }else {
            tbFollowDTO = (TbFollowDTO) arguments.get("tbFollowDTO");
            if (StringUtils.isNotNull(tbFollowDTO.getOtherText())){
                otherText = GsonUtils.fromJson(tbFollowDTO.getOtherText(),List.class);
            }else {
                otherText = new ArrayList();
            }
            inhabitantDTO = viewModel.getInhabitantRepository().findByField("ID",tbFollowDTO.getPersonID());
            if (inhabitantDTO == null){
                Utils.Toast(context,"请先更新病人数据！");
                hideAddFragment();
            }else {
                echo();
            }
        }

    }

    /**
     * 保存数据
     */
    private void save(){
        //当前饮酒量
        tbFollowDTO.setDailyAlcoholIntake(binding.editTextTextPersonName31.getText().toString());

        //当前吸烟数
        tbFollowDTO.setSmoking(binding.editTextTextPersonName30.getText().toString());

        //化疗方案
        tbFollowDTO.setChemotherapyRegimen(binding.editTextTextPersonName9.getText().toString());

        //药品剂型（1 固定剂量复合制剂，2 散装药，4 板式组合药8 注射剂 注：不选传0）
        int dosage = 0;
        if (binding.radioButton61.isChecked())
            dosage+=1;
        if (binding.radioButton62.isChecked())
            dosage+=2;
        if (binding.radioButton63.isChecked())
            dosage+=4;
        if (binding.radioButton64.isChecked())
            dosage+=8;
        tbFollowDTO.setDosage(String.valueOf(dosage));

        //漏服药次数
        tbFollowDTO.setMissedMedNum(binding.editTextTextPersonName32.getText().toString());

        //用法（1 每日，2 间隔 注：不选传0）
        int checkedRadioButtonId = binding.radioGroupPlus06.getCheckedRadioButtonId();
        String usage = "0";
        switch (checkedRadioButtonId){
            case R.id.radioButton59:
                usage = "1";
                break;
            case R.id.radioButton60:
                usage = "2";
                break;
        }
        tbFollowDTO.setUsage(usage);

        //药物不良反应（1 无，2 有）
        checkedRadioButtonId = binding.radioGroupPlus0211.getCheckedRadioButtonId();
        String adverseDrugReactions = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton2401:
                adverseDrugReactions = "1";
                break;
            case R.id.radioButton2411:
                adverseDrugReactions = "2";
                setMap("AdverseDrugReactions",binding.editTextTextPersonName10.getText().toString());
                break;
        }
        tbFollowDTO.setAdverseDrugReactions(adverseDrugReactions);

        //并发症或合并症（1 无，2 有）
        checkedRadioButtonId = binding.radioGroupPlus02111.getCheckedRadioButtonId();
        String complication = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton24011:
                complication = "1";
                break;
            case R.id.radioButton24111:
                complication = "2";
                setMap("Complication",binding.editTextTextPersonName11.getText().toString());
                break;
        }
        tbFollowDTO.setComplication(complication);

        //医生信息
        tbFollowDTO.setDoctorID(viewModel.getUserInfo().getDId());
        tbFollowDTO.setDoctorName(viewModel.getUserInfo().getDoctorName());

        //随访时间
        tbFollowDTO.setFollowUpDate(binding.textView271.getText().toString());

        //处理意见
        tbFollowDTO.setFollowUpRemarks(binding.editTextTextPersonName27.getText().toString());

        //下次随访日期
        tbFollowDTO.setNextFollowUpDate(binding.textView272.getText().toString());

        //督导人员
        checkedRadioButtonId = binding.radioGroupPlus022.getCheckedRadioButtonId();
        String supervisor = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton243:
                supervisor = "1";
                break;
            case R.id.radioButton244:
                supervisor = "2";
                break;
            case R.id.radioButton245:
                supervisor = "4";
                break;
            case R.id.radioButton246:
                supervisor = "8";
                break;
        }
        tbFollowDTO.setSupervisor(supervisor);

        //症状及体征
        tbFollowDTO.setSymptom(totalSymptom());

        //2周内随访结果
        tbFollowDTO.setTranOut(binding.editTextTextPersonName25.getText().toString());

        //治疗月序
        tbFollowDTO.setTreatmentMonthOrder(binding.editTextTextPersonName2.getText().toString());

        //随访方式(1 门诊，2 家庭 4电话)
        checkedRadioButtonId = binding.radioGroupPlus021.getCheckedRadioButtonId();
        String wayUp = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton240:
                wayUp = "1";
                break;
            case R.id.radioButton241:
                wayUp = "2";
                break;
            case R.id.radioButton242:
                wayUp = "4";
                break;
        }
        tbFollowDTO.setWayUp(wayUp);

        //停止治疗时间
        tbFollowDTO.setStopTreatDate(binding.textView270.getText().toString());

        //停止治疗原因
        checkedRadioButtonId = binding.radioGroupPlus23.getCheckedRadioButtonId();
        String stopTreatReason = "";
        switch (checkedRadioButtonId){
            case R.id.radioButton258:
                stopTreatReason = "1";
                break;
            case R.id.radioButton259:
                stopTreatReason = "2";
                break;
            case R.id.radioButton256:
                stopTreatReason = "4";
                break;
            case R.id.radioButton257:
                stopTreatReason = "8";
                break;
        }
        tbFollowDTO.setStopTreatReason(stopTreatReason);

        //应访视次数
        tbFollowDTO.setShouldFollowUpCnt(binding.editTextTextPersonName81.getText().toString());

        //实际访视次数
        tbFollowDTO.setActualFollowUpCnt(binding.editTextTextPersonName82.getText().toString());

        //应服药
        tbFollowDTO.setShouldMedicationCnt(binding.editTextTextPersonName83.getText().toString());

        //实际服药
        tbFollowDTO.setActualMedicationCnt(binding.editTextTextPersonName84.getText().toString());

        //评估医生
        tbFollowDTO.setAppraiseDoctorID(viewModel.getUserInfo().getDId());
        tbFollowDTO.setAppraiseDoctorName(viewModel.getUserInfo().getDoctorName());

        tbFollowDTO.setOtherText(GsonUtils.toJson(otherText));

    }

    /**
     * 数据回显
     */
    private void echo() {
        setInhabitantView();

        //治疗月序
        if (StringUtils.isNotNull(tbFollowDTO.getTreatmentMonthOrder()))
            binding.editTextTextPersonName2.setText(tbFollowDTO.getTreatmentMonthOrder());

        //督导人员
        if (StringUtils.isNotNull(tbFollowDTO.getSupervisor())){
            switch (tbFollowDTO.getSupervisor()){
                case "1":
                    binding.radioGroupPlus022.check(R.id.radioButton243);
                    break;
                case "2":
                    binding.radioGroupPlus022.check(R.id.radioButton244);
                    break;
                case "4":
                    binding.radioGroupPlus022.check(R.id.radioButton245);
                    break;
                case "8":
                    binding.radioGroupPlus022.check(R.id.radioButton246);
                    break;
            }
        }

        //随访方式
        if (StringUtils.isNotNull(tbFollowDTO.getWayUp())){
            switch (tbFollowDTO.getWayUp()){
                case "1":
                    binding.radioGroupPlus021.check(R.id.radioButton240);
                    break;
                case "2":
                    binding.radioGroupPlus021.check(R.id.radioButton241);
                    break;
                case "4":
                    binding.radioGroupPlus021.check(R.id.radioButton242);
                    break;
            }
        }

        //症状
        if (StringUtils.isNotNull(tbFollowDTO.getSymptom())
                && !tbFollowDTO.getSymptom().equals("0")){
            List<Integer> list = Utils.divisionBinary(Integer.valueOf(tbFollowDTO.getSymptom()));
            for (Integer integer : list) {
                switch (integer){
                    case 1:
                        binding.radioButton27.setChecked(true);
                        binding.editTextTextPersonName8.setEnabled(false);
                        break;
                    case 2:
                        binding.radioButton28.setChecked(true);
                        break;
                    case 3:
                        binding.radioButton29.setChecked(true);
                        break;
                    case 4:
                        binding.radioButton32.setChecked(true);
                        break;
                    case 5:
                        binding.radioButton33.setChecked(true);
                        break;
                    case 6:
                        binding.radioButton34.setChecked(true);
                        break;
                    case 7:
                        binding.radioButton35.setChecked(true);
                        break;
                    case 8:
                        binding.radioButton36.setChecked(true);
                        break;
                    case 9:
                        binding.radioButton37.setChecked(true);
                        break;
                    case 10:
                        binding.radioButton38.setChecked(true);
                        break;
                    case 11:
                        binding.radioButton39.setChecked(true);
                        break;
                    case 12:
                        if (getMap("Symptom") != null){
                            String symptom = getMap("Symptom");
                            binding.editTextTextPersonName8.setEnabled(true);
                            binding.editTextTextPersonName8.setText(symptom);
                        }
                        break;
                }
            }
        }

        //吸烟
        if (StringUtils.isNotNull(tbFollowDTO.getSmoking()))
            binding.editTextTextPersonName30.setText(tbFollowDTO.getSmoking());

        //饮酒
        if (StringUtils.isNotNull(tbFollowDTO.getDailyAlcoholIntake()))
            binding.editTextTextPersonName31.setText(tbFollowDTO.getDailyAlcoholIntake());

        //化疗方案
        if (StringUtils.isNotNull(tbFollowDTO.getChemotherapyRegimen()))
            binding.editTextTextPersonName9.setText(tbFollowDTO.getChemotherapyRegimen());

        //用法
        if (StringUtils.isNotNull(tbFollowDTO.getUsage())){
            switch (tbFollowDTO.getUsage()){
                case "1":
                    binding.radioGroupPlus06.check(R.id.radioButton59);
                    break;
                case "2":
                    binding.radioGroupPlus06.check(R.id.radioButton60);
                    break;
            }
        }

        //药品剂型
        if (StringUtils.isNotNull(tbFollowDTO.getDosage()) && !tbFollowDTO.getDosage().equals("0")){
            List<Integer> list = Utils.divisionBinary(Integer.valueOf(tbFollowDTO.getDosage()));
            for (Integer integer : list) {
                switch (integer){
                    case 1:
                        binding.radioButton61.setChecked(true);
                        break;
                    case 2:
                        binding.radioButton62.setChecked(true);
                        break;
                    case 3:
                        binding.radioButton63.setChecked(true);
                        break;
                    case 4:
                        binding.radioButton64.setChecked(true);
                        break;
                }
            }
        }

        //漏服药次数
        if (StringUtils.isNotNull(tbFollowDTO.getMissedMedNum()))
            binding.editTextTextPersonName32.setText(tbFollowDTO.getMissedMedNum());

        //药物不良反应
        if (StringUtils.isNotNull(tbFollowDTO.getAdverseDrugReactions())){
            switch (tbFollowDTO.getAdverseDrugReactions()){
                case "1":
                    binding.radioGroupPlus0211.check(R.id.radioButton2401);
                    binding.editTextTextPersonName10.setEnabled(false);
                    break;
                case "2":
                    binding.radioGroupPlus0211.check(R.id.radioButton2411);
                    binding.editTextTextPersonName10.setEnabled(true);
                    if(getMap("AdverseDrugReactions") != null){
                        binding.editTextTextPersonName10.setText(getMap("AdverseDrugReactions"));
                    }
                    break;
            }
        }

        //并发症或合并症
        if (StringUtils.isNotNull(tbFollowDTO.getComplication())){
            switch (tbFollowDTO.getComplication()){
                case "1":
                    binding.radioGroupPlus02111.check(R.id.radioButton24011);
                    binding.editTextTextPersonName11.setEnabled(false);
                    break;
                case "2":
                    binding.radioGroupPlus02111.check(R.id.radioButton24111);
                    binding.editTextTextPersonName11.setEnabled(true);
                    if(getMap("Complication") != null ){
                        binding.editTextTextPersonName11.setText(getMap("Complication"));
                    }
                    break;
            }
        }

        //2周内随访，随访结果
        if (StringUtils.isNotNull(tbFollowDTO.getTranOut()))
            binding.editTextTextPersonName25.setText(tbFollowDTO.getTranOut());

        //处理意见
        if (StringUtils.isNotNull(tbFollowDTO.getFollowUpRemarks()))
            binding.editTextTextPersonName27.setText(tbFollowDTO.getFollowUpRemarks());

        //停止治疗时间
        if (StringUtils.isNotNull(tbFollowDTO.getStopTreatDate()))
            binding.textView270.setText(tbFollowDTO.getStopTreatDate());

        //停止治疗原因
        if (StringUtils.isNotNull(tbFollowDTO.getStopTreatReason())){
            switch (tbFollowDTO.getStopTreatReason()){
                case "1":
                    binding.radioGroupPlus23.check(R.id.radioButton258);
                    break;
                case "2":
                    binding.radioGroupPlus23.check(R.id.radioButton259);
                    break;
                case "4":
                    binding.radioGroupPlus23.check(R.id.radioButton256);
                    break;
                case "8":
                    binding.radioGroupPlus23.check(R.id.radioButton257);
                    break;
            }
        }

        //应访视患者
        if (StringUtils.isNotNull(tbFollowDTO.getShouldFollowUpCnt()))
            binding.editTextTextPersonName81.setText(tbFollowDTO.getShouldFollowUpCnt());

        //实际访视
        if (StringUtils.isNotNull(tbFollowDTO.getActualFollowUpCnt()))
            binding.editTextTextPersonName82.setText(tbFollowDTO.getActualFollowUpCnt());

        //患者在疗程中应服药
        if (StringUtils.isNotNull(tbFollowDTO.getShouldMedicationCnt()))
            binding.editTextTextPersonName83.setText(tbFollowDTO.getShouldMedicationCnt());

        //患者在疗程中实际服药
        if (StringUtils.isNotNull(tbFollowDTO.getActualMedicationCnt()))
            binding.editTextTextPersonName84.setText(tbFollowDTO.getActualMedicationCnt());

        //评估医生
        if (StringUtils.isNotNull(tbFollowDTO.getAppraiseDoctorName()))
            binding.editTextTextPersonName85.setText(tbFollowDTO.getAppraiseDoctorName());

        //随访时间
        if (StringUtils.isNotNull(tbFollowDTO.getFollowUpDate()))
            binding.textView271.setText(tbFollowDTO.getFollowUpDate());

        //下次随访时间
        if (StringUtils.isNotNull(tbFollowDTO.getNextFollowUpDate()))
            binding.textView272.setText(tbFollowDTO.getNextFollowUpDate());

        //随访医生
        if (StringUtils.isNotNull(tbFollowDTO.getDoctorName()))
            binding.editTextTextPersonName34.setText(tbFollowDTO.getDoctorName());

    }

    private void setInhabitantView(){
        binding.textView177.setText(inhabitantDTO.getNAME());
        if ("1".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("男");
        else if ("2".equals(inhabitantDTO.getSEX()))
            binding.textView179.setText("女");
        binding.textView183.setText(inhabitantDTO.getTEL());
        binding.textView184.setText(inhabitantDTO.getIDCARD());
    }

    private void clearInhabitantView(){
        binding.textView177.setText("");
        binding.textView179.setText("");
        binding.textView183.setText("");
        binding.textView184.setText("");
        Utils.Toast(context,"未查到该身份证的信息，请同步居民信息后再添加！");
    }

    /**
     * 计算症状总值
     * @return
     */
    private String totalSymptom() {
        int symptom = 0;
        if (binding.radioButton27.isChecked())
            return "1";
        if (binding.radioButton28.isChecked())
            symptom+=2;
        if (binding.radioButton29.isChecked())
            symptom+=4;
        if (binding.radioButton32.isChecked())
            symptom+=8;
        if (binding.radioButton33.isChecked())
            symptom+=16;
        if (binding.radioButton34.isChecked())
            symptom+=32;
        if (binding.radioButton35.isChecked())
            symptom+=64;
        if (binding.radioButton36.isChecked())
            symptom+=128;
        if (binding.radioButton37.isChecked())
            symptom+=256;
        if (binding.radioButton38.isChecked())
            symptom+=512;
        if (binding.radioButton39.isChecked())
            symptom+=1024;
        if (StringUtils.isNotNull(binding.editTextTextPersonName8.getText().toString())){
            symptom+=2048;
            setMap("Symptom",binding.editTextTextPersonName8.getText().toString());
        }
        return String.valueOf(symptom);
    }

    /**
     * 隐藏或关闭Fragment
     */
    private void hideAddFragment() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.setCustomAnimations(0, R.anim.fragment_slide_down);
        ft.hide(this);
        ft.commitAllowingStateLoss();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == binding.radioButton27.getId()){
            if (isChecked){
                binding.editTextTextPersonName8.setEnabled(false);
            }else {
                binding.editTextTextPersonName8.setEnabled(true);
            }
        }
        if (binding.radioButton27.isChecked() && buttonView.getId() != binding.radioButton27.getId()){
            Utils.Toast(context,"请先取消没有症状选项！");
            buttonView.setChecked(false);
            return;
        }
        if (binding.radioButton28.isChecked()
                || binding.radioButton29.isChecked()
                || binding.radioButton32.isChecked()
                || binding.radioButton33.isChecked()
                || binding.radioButton34.isChecked()
                || binding.radioButton35.isChecked()
                || binding.radioButton36.isChecked()
                || binding.radioButton37.isChecked()
                || binding.radioButton38.isChecked()
                || binding.radioButton39.isChecked()){
            if (buttonView.getId() == binding.radioButton27.getId()){
                Utils.Toast(context,"请先取消其他选项！");
                buttonView.setChecked(false);
                return;
            }
        }
    }

    public String getMap(String str){
        for (Map<String, Object> map : otherText) {
            String attrName = map.get("AttrName").toString();
            String otherText = map.get("OtherText").toString();
            if (attrName.equals(str))
                return otherText;
        }
        return null;
    }

    /**
     * 设置other值
     * @param key
     * @param value
     */
    private void setMap(String key, String value) {
        Map<String,Map> keys = new HashMap<>();
        for (Map<String, Object> map : otherText) {
            String k = map.get("AttrName").toString();
            keys.put(k,map);
        }
        if (keys.keySet().contains(key)){
            Map map = keys.get(key);
            map.put("OtherText",value);
        }else {
            Map map = new HashMap();
            map.put("AttrName",key);
            map.put("OtherText",value);
            otherText.add(map);
        }
    }

}
